package com.trainingcloud.utils;

import com.auth0.jwt.algorithms.Algorithm;
import com.auth0.jwt.JWT;
import com.auth0.jwt.JWTVerifier;
import com.auth0.jwt.interfaces.DecodedJWT;

import java.util.Calendar;
import java.util.HashMap;
import java.util.Map;

/**
 * @Classname TokenUtil
 * @Date 2022/10/8 15:55
 * @Author 纸鹤超努力
 */
public class TokenUtil {

    private static String SEC_KEY = "@#abc";

    private static JWTVerifier JWTVE = JWT.require(Algorithm.HMAC256(SEC_KEY)).build();

//    创建Token
    public static String getToken(int exptime,Map<String,String> data){
        Calendar calendar =Calendar.getInstance();
        calendar.add(Calendar.DATE,exptime);
        String token = JWT.create()
                .withPayload(data)
                .withExpiresAt(calendar.getTime())
                .sign(Algorithm.HMAC256(SEC_KEY));
        return token;
    }

//    token数据解析
    public static String getItem(String token,String key){
        DecodedJWT decode =JWTVE.verify(token);
        String value =decode.getClaims().get(key).asString();
        return value;
    }

    public static void main(String[] args) {
        String token = "eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJ0ZXN0IjoidGVzdCBkYXRhIiwiZXhwIjoxNjY1OTA2MDUzfQ.Tw2VmsZN1ZM2oWM9MNRbulF2--VH9sehlrQ3Uc9sclY";
        String test = getItem(token,"test");
        System.out.println(test);
//        Map<String,String> data = new HashMap<>();
//        data.put("test","test data");
//        String token = getToken(7,data);
//        System.out.println(token);
    }
}
